package com.dm.wallpaper.library.database;

import com.dm.wallpaper.library.abilityPackage.WallpaperBoardApplication;
import com.dm.wallpaper.library.helpers.JsonHelper;
import com.dm.wallpaper.library.helpers.TimeHelper;
import com.dm.wallpaper.library.items.Filter;
import com.dm.wallpaper.library.items.Category;
import com.dm.wallpaper.library.items.PopupItem;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.dm.wallpaper.library.utils.ImageSize;
import com.dm.wallpaper.library.utils.Log;
import com.dm.wallpaper.library.utils.SystemUtils;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;
import org.apache.commons.lang3.StringEscapeUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Database extends DatabaseHelper {
    private static final String DATABASE_NAME = "wallpaper_board_database.db";
    private static final int DATABASE_VERSION = 5;
    private RdbStore rdbStore;
    private static WeakReference<Database> mDatabase;
    private final Context mContext;
    private static StoreConfig config = StoreConfig.newDefaultConfig(DATABASE_NAME);

    private static final String TABLE_CATEGORIES = "categories";
    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    private static final String KEY_SELECTED = "selected";
    private static final String KEY_MUZEI_SELECTED = "muzeiSelected";

    private static final String TABLE_WALLPAPERS = "wallpapers";
    public static final String KEY_AUTHOR = "author";
    private static final String KEY_URL = "url";
    private static final String KEY_THUMB_URL = "thumbUrl";
    private static final String KEY_MIME_TYPE = "mimeType";
    private static final String KEY_SIZE = "size";
    private static final String KEY_COLOR = "color";
    private static final String KEY_WIDTH = "width";
    private static final String KEY_HEIGHT = "height";
    private static final String KEY_COUNT = "count";
    public static final String KEY_CATEGORY = "category";
    private static final String KEY_FAVORITE = "favorite";
    private static final String KEY_ADDED_ON = "addedOn";

    public Database(Context context) {
        super(context);
        mContext = context;
        rdbStore = getRdbStore(config, DATABASE_VERSION, callback, null);
    }

    public static Database get() {
        if (mDatabase == null || mDatabase.get() == null) {
            mDatabase = new WeakReference<>(new Database(WallpaperBoardApplication.getInstance()));
        }
        return mDatabase.get();
    }

    RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore store) {
            String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_CATEGORIES + "(" +
                    KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                    KEY_NAME + " TEXT NOT NULL," +
                    KEY_THUMB_URL + " TEXT NOT NULL, " +
                    KEY_SELECTED + " INTEGER DEFAULT 1," +
                    KEY_MUZEI_SELECTED + " INTEGER DEFAULT 1, " +
                    KEY_COUNT + " INTEGER DEFAULT 0," +
                    KEY_COLOR + " INTEGER DEFAULT 0," +
                    "UNIQUE (" + KEY_ID + "))";
            String CREATE_TABLE_WALLPAPER = "CREATE TABLE IF NOT EXISTS " + TABLE_WALLPAPERS + "(" +
                    KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_AUTHOR + " TEXT, " +
                    KEY_URL + " TEXT NOT NULL, " +
                    KEY_THUMB_URL + " TEXT NOT NULL, " +
                    KEY_MIME_TYPE + " TEXT, " +
                    KEY_SIZE + " INTEGER DEFAULT 0, " +
                    KEY_COLOR + " INTEGER DEFAULT 0, " +
                    KEY_WIDTH + " INTEGER DEFAULT 0, " +
                    KEY_HEIGHT + " INTEGER DEFAULT 0, " +
                    KEY_CATEGORY + " TEXT NOT NULL," +
                    KEY_FAVORITE + " INTEGER DEFAULT 0," +
                    KEY_ADDED_ON + " TEXT NOT NULL, " +
                    "UNIQUE (" + KEY_ID + "))";
            store.executeSql(CREATE_TABLE_CATEGORY);
            store.executeSql(CREATE_TABLE_WALLPAPER);
        }

        @Override
        public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
            Log.i("Database.onUpgrade([store, oldVersion, newVersion]):119");
            if (newVersion == 5) {
                Preferences.get().clearPreferences();
            }
            resetDatabase(store);
        }
    };

    private void resetDatabase(RdbStore db) {
        Log.i("MiDatabase.resetDatabase([db]):99");
        List<String> tables = new ArrayList<>();
        ResultSet cursor = db.querySql("SELECT name FROM sqlite_master WHERE type=\'table\'", null);
        if (cursor.goToFirstRow()) {
            do {
                tables.add(cursor.getString(0));
            } while (cursor.goToNextRow());
        }
        cursor.close();

        List<String> mFavoriteUrlsBackup;
        mFavoriteUrlsBackup = new ArrayList<>();

        if (cursor.goToFirstRow()) {
            do {
                mFavoriteUrlsBackup.add(cursor.getString(0));
            } while (cursor.goToNextRow());
        }
        cursor.close();

        for (int i = 0; i < tables.size(); i++) {
            try {
                String dropQuery = "DROP TABLE IF EXISTS " + tables.get(i);
                if (!tables.get(i).equalsIgnoreCase("SQLITE_SEQUENCE"))
                    db.executeSql(dropQuery);
            } catch (Exception ignored) {
            }
        }
        mDatabase.clear();
        mDatabase = null;
        get();
    }

    public void addWallpapers(List<?> list) {
        String query = "INSERT OR IGNORE INTO " + TABLE_WALLPAPERS + " (" + KEY_NAME + "," + KEY_AUTHOR + "," + KEY_URL + ","
                + KEY_THUMB_URL + "," + KEY_CATEGORY + "," + KEY_ADDED_ON + "," + KEY_FAVORITE + ") VALUES (?,?,?,?,?,?,?);";
        Statement statement = rdbStore.buildStatement(query);
        for (int i = 0; i < list.size(); i++) {
            Wallpaper wallpaper;
            if (list.get(i) instanceof Wallpaper) {
                wallpaper = (Wallpaper) list.get(i);
            } else {
                wallpaper = JsonHelper.getWallpaper(list.get(i));
            }

            if (wallpaper != null) {
                if (wallpaper.getUrl() != null) {
                    String name = wallpaper.getName();
                    if (name == null) name = "";

                    statement.setString(1, name);

                    if (wallpaper.getAuthor() != null) {
                        statement.setString(2, wallpaper.getAuthor());
                    } else {
                        statement.setNull(2);
                    }
                    statement.setString(3, wallpaper.getUrl());
                    statement.setString(4, wallpaper.getThumbUrl());
                    statement.setString(5, wallpaper.getCategory());
                    statement.setString(6, TimeHelper.getLongDateTime());
                    statement.setLong(7, wallpaper.getFavorite());
                    statement.execute();
                }
            }
        }
    }

    private String getSortBy(PopupItem.Type type) {
        switch (type) {
            case SORT_OLDEST:
                return KEY_ADDED_ON + ", " + KEY_ID + " DESC";
            case SORT_NAME:
                return KEY_NAME;
            case SORT_RANDOM:
                return "RANDOM()";
            default:
                return KEY_ADDED_ON + " DESC";
        }
    }


    public List<Wallpaper> getWallpapers() {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return new ArrayList<>();
        }

        String query = "SELECT * FROM wallpapers  ORDER BY  " + getSortBy(Preferences.get().getSortBy());
        ResultSet resultSet = rdbStore.querySql(query, null);
        List<Wallpaper> wallpapers = new ArrayList<>();
        if (resultSet.goToFirstRow()) {
            do {
                Wallpaper wallpaper = Wallpaper.Builder()
                        .id(resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID)))
                        .name(resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME)))
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .favorite(resultSet.getInt(resultSet.getColumnIndexForName(KEY_FAVORITE)))
                        .addedOn(resultSet.getString(resultSet.getColumnIndexForName(KEY_ADDED_ON))).build();
                wallpapers.add(wallpaper);
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpapers;
    }

    public void favoriteWallpaper(int id, int b) {
        //TODO 修改不成功。查询库里面的数量为 0
        String query = "UPDATE " + TABLE_WALLPAPERS + " SET " + KEY_FAVORITE + " = ? "
                + "WHERE " + KEY_ID + " = ? ";
        Statement statement = rdbStore.buildStatement(query);
        statement.setLong(1, b);
        statement.setLong(2, id);
        statement.execute();

    }

    public void updateWallpaper(int localIdID, int size, ImageSize dimensions) {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return;
        }
        if (dimensions == null) {
            return;
        }
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putInteger(KEY_WIDTH, dimensions.getWidth());
        valuesBucket.putInteger(KEY_HEIGHT, dimensions.getHeight());
        valuesBucket.putInteger(KEY_SIZE, size);
        RdbPredicates rdbPredicates = new RdbPredicates(TABLE_WALLPAPERS);
        rdbPredicates.equalTo(KEY_ID, localIdID);
        rdbStore.update(valuesBucket, rdbPredicates);
    }


    public List<Wallpaper> getLatestWallpapers() {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return new ArrayList<>();
        }
        List<Wallpaper> wallpapers = new ArrayList<>();

        String query = "SELECT * FROM wallpapers ORDER BY " + KEY_ADDED_ON + " DESC, " + KEY_ID + " LIMIT 15";
        ResultSet resultSet = rdbStore.querySql(query, null);

//        Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, null, null, null, null,
//                KEY_ADDED_ON + " DESC, " + KEY_ID,
//                String.valueOf(WallpaperBoardApplication.getConfig().getLatestWallpapersDisplayMax()));
        if (resultSet.goToFirstRow()) {
            do {
                int width = resultSet.getInt(resultSet.getColumnIndexForName(KEY_WIDTH));
                int height = resultSet.getInt(resultSet.getColumnIndexForName(KEY_HEIGHT));
                ImageSize dimensions = null;
                if (width > 0 && height > 0) {
                    dimensions = new ImageSize(width, height);
                }
                int id = resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID));
                String name = resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME));
                if (name.length() == 0) {
                    name = "Wallpaper " + id;
                }
                Wallpaper wallpaper = Wallpaper.Builder()
                        .id(id)
                        .name(name)
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .favorite(resultSet.getInt(resultSet.getColumnIndexForName(KEY_FAVORITE)))
                        .dimensions(dimensions)
                        .mimeType(resultSet.getString(resultSet.getColumnIndexForName(KEY_MIME_TYPE)))
                        .size(resultSet.getInt(resultSet.getColumnIndexForName(KEY_SIZE)))
                        .color(resultSet.getInt(resultSet.getColumnIndexForName(KEY_COLOR)))
                        .build();
                wallpapers.add(wallpaper);
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpapers;
    }

    public List<Wallpaper> getFavoritesWallpapers() {
        String query = "SELECT * FROM " + TABLE_WALLPAPERS + " WHERE " + TABLE_WALLPAPERS + "." + KEY_FAVORITE + " = 1";
        ResultSet resultSet = rdbStore.querySql(query, null);
        List<Wallpaper> wallpapers = new ArrayList<>();
        if (resultSet.goToFirstRow()) {
            do {
                Wallpaper.Builder builder = Wallpaper.Builder()
                        .id(resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID)))
                        .name(resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME)))
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .favorite(resultSet.getInt(resultSet.getColumnIndexForName(KEY_FAVORITE)));
                wallpapers.add(builder.build());
                Log.i("Database.getWallpapers([]):249      " + wallpapers);
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpapers;
    }


    public List<Category> getCategorys() {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return new ArrayList<>();
        }

        String query = "SELECT * FROM " + TABLE_CATEGORIES;
        ResultSet resultSet = rdbStore.querySql(query, null);
        List<Category> wallpapers = new ArrayList<>();
        if (resultSet.goToFirstRow()) {
            do {
                Category.Builder builder = Category.Builder()
                        .id(resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID)))
                        .name(resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .count(resultSet.getInt(resultSet.getColumnIndexForName(KEY_COUNT)))
                        .selected(resultSet.getInt(resultSet.getColumnIndexForName(KEY_SELECTED)))
                        .muzeiSelected(resultSet.getInt(resultSet.getColumnIndexForName(KEY_MUZEI_SELECTED)));
                wallpapers.add(builder.build());
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpapers;
    }


    public List<Wallpaper> getFilteredWallpapers(Filter filter) {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return new ArrayList<>();
        }

        StringBuilder condition = new StringBuilder();
        for (int i = 0; i < filter.size(); i++) {
            Filter.Options options = filter.get(i);
            if (options != null) {
                if (condition.length() > 0) {
                    condition.append(" OR ").append("LOWER(")
                            .append(options.getColumn().getName())
                            .append(")").append(" LIKE " + "\"%" + SystemUtils.escapeQueryChars(options.getQuery().toLowerCase(Locale.getDefault())) + "%\"");
                } else {
                    condition.append("LOWER(")
                            .append(options.getColumn().getName()).append(")")
                            .append(" LIKE " + "\"%" + SystemUtils.escapeQueryChars(options.getQuery().toLowerCase(Locale.getDefault())) + "%\"");
                }
            }
        }
        String query = "SELECT * FROM wallpapers  where  " + condition.toString() + "   ORDER BY  " + getSortBy(Preferences.get().getSortBy());
        Log.i("Database.searchWallpaperView([filter]):351     " + query);
        ResultSet resultSet = rdbStore.querySql(query, null);
        List<Wallpaper> wallpapers = new ArrayList<>();
        if (resultSet.goToFirstRow()) {
            do {
                Wallpaper wallpaper = Wallpaper.Builder()
                        .id(resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID)))
                        .name(resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME)))
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .favorite(resultSet.getInt(resultSet.getColumnIndexForName(KEY_FAVORITE)))
                        .build();
                wallpapers.add(wallpaper);
                Log.i("Database.getFilteredWallpapers([filter]):387  " + wallpaper.getName() + "         " + wallpaper.getCategory());
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpapers;
    }


    public int getFilteredWallpapersCount(Filter filter) {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return 0;
        }

        StringBuilder condition = new StringBuilder();
        for (int i = 0; i < filter.size(); i++) {
            Filter.Options options = filter.get(i);
            if (options != null) {
                if (condition.length() > 0) {
                    condition.append(" OR ").append("LOWER(")
                            .append(options.getColumn().getName())
                            .append(")").append(" LIKE " + "\"%" + SystemUtils.escapeQueryChars(options.getQuery().toLowerCase(Locale.getDefault())) + "%\"");
                } else {
                    condition.append("LOWER(")
                            .append(options.getColumn().getName()).append(")")
                            .append(" LIKE " + "\"%" + SystemUtils.escapeQueryChars(options.getQuery().toLowerCase(Locale.getDefault())) + "%\"");
                }
            }
        }
        String query = "SELECT * FROM wallpapers  where  " + condition.toString() + "   ORDER BY  " + getSortBy(Preferences.get().getSortBy());
        ResultSet resultSet = rdbStore.querySql(query, null);

        return resultSet.getRowCount();
    }

    public void addCategory(List<?> list) {

        String query = "INSERT OR IGNORE INTO " + TABLE_CATEGORIES + " (" + KEY_NAME + "," + KEY_SELECTED + "," + KEY_MUZEI_SELECTED + ","
                + KEY_COUNT + "," + KEY_ID + "," + KEY_COLOR + "," + KEY_THUMB_URL + ") VALUES (?,?,?,?,?,?,?);";
        Statement statement = rdbStore.buildStatement(query);
        for (int i = 0; i < list.size(); i++) {
            Category category;
            if (list.get(i) instanceof Category) {
                category = (Category) list.get(i);
            } else {
                category = JsonHelper.getCategory(list.get(i));
            }

            if (category != null) {
                String name = category.getName();
                String thumbUrl = category.getThumbUrl();
                if (name == null) name = "";
                if (thumbUrl == null) thumbUrl = "";
                statement.setString(1, name);
                statement.setLong(2, category.getSelected());
                statement.setLong(3, category.getMuzeiSelected());
                statement.setLong(4, category.getCount());
                statement.setLong(5, category.getId());
                statement.setLong(6, category.getColor());
                statement.setString(7, thumbUrl);
                statement.execute();
            }
        }
    }

    public Wallpaper getWallpaperByLocalIdID(int id) {
        if (rdbStore == null || !rdbStore.isOpen()) {
            Log.e("数据库出现问题了,请及时查找原因");
            return null;
        }

        Wallpaper wallpaper = null;

        String query = "SELECT * FROM " + TABLE_WALLPAPERS + " where " + KEY_ID + " = " + "'" + id + "'";
        Log.i("Database.searchWallpaperView([filter]):351     " + query);
        ResultSet resultSet = rdbStore.querySql(query, null);


        if (resultSet.goToFirstRow()) {
            do {
                int width = resultSet.getInt(resultSet.getColumnIndexForName(KEY_WIDTH));
                int height = resultSet.getInt(resultSet.getColumnIndexForName(KEY_HEIGHT));
                ImageSize dimensions = new ImageSize(width, height);
                int wId = resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID));
                String name = resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME));
                if (name.length() == 0) {
                    name = "Wallpaper " + wId;
                }
                wallpaper = Wallpaper.Builder()
                        .id(wId)
                        .name(name)
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .favorite(resultSet.getInt(resultSet.getColumnIndexForName(KEY_FAVORITE)))
                        .dimensions(dimensions)
                        .mimeType(resultSet.getString(resultSet.getColumnIndexForName(KEY_MIME_TYPE)))
                        .size(resultSet.getInt(resultSet.getColumnIndexForName(KEY_SIZE)))
                        .color(resultSet.getInt(resultSet.getColumnIndexForName(KEY_COLOR)))
                        .build();
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpaper;
    }

    public void selectCategoryForMuzei(int id, boolean isSelected) {
//        ValuesBucket values = new ValuesBucket();
//        values.putInteger(KEY_MUZEI_SELECTED, isSelected ? 1 : 0);
//        RdbPredicates absRdbPredicates = new RdbPredicates(TABLE_CATEGORIES).equalTo(KEY_ID, String.valueOf(id));
//        int update = rdbStore.update(values, absRdbPredicates);
//        Log.i("Database.selectCategoryForMuzei([id, isSelected]):416   " + update);

        String query = "UPDATE " + TABLE_CATEGORIES + " SET " + KEY_MUZEI_SELECTED + " = ? "
                + "WHERE " + KEY_ID + " = ? ";
        Statement statement = rdbStore.buildStatement(query);
        statement.setLong(1, isSelected ? 1 : 0);
        statement.setLong(2, id);
        statement.execute();
    }


//    public void selectCategory(int id, boolean isSelected) {
////        ValuesBucket values = new ValuesBucket();
////        values.putInteger(KEY_SELECTED, isSelected ? 1 : 0);
////        RdbPredicates absRdbPredicates = new RdbPredicates(TABLE_CATEGORIES).equalTo(KEY_ID, String.valueOf(id));
////        int update = rdbStore.update(values, absRdbPredicates);
////        Log.i("Database.selectCategory([id, isSelected]):424    "+update);
//
//        String query = "UPDATE " + TABLE_CATEGORIES + " SET " + KEY_MUZEI_SELECTED + " = ? "
//                + "WHERE " + KEY_ID + " = ? ";
//        Statement statement = rdbStore.buildStatement(query);
//        statement.setLong(1, isSelected ? 1 : 0);
//        statement.setLong(2, id);
//        statement.execute();
//
//    }


    public int getWallpapersCount() {
        RdbPredicates absRdbPredicates = new RdbPredicates(TABLE_WALLPAPERS);
        ResultSet resultSet = rdbStore.query(absRdbPredicates, null);
        int rowCount = resultSet.getRowCount();
        return rowCount;
    }


    public Wallpaper getRandomWallpaper() {
        Wallpaper wallpaper = null;
        List<String> selected = getSelectedCategories(true);
        List<String> selection = new ArrayList<>();
        if (selected.size() == 0) return null;

        StringBuilder CONDITION = new StringBuilder();
        for (String item : selected) {
            selection.add("%" + item.toLowerCase(Locale.getDefault()) + "%");

            if (CONDITION.length() > 0) {
                CONDITION.append(" OR ").append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE " + selection.size());
            } else {
                CONDITION.append("LOWER(").append(KEY_CATEGORY).append(")").append(" LIKE " + selection.size());
            }
        }

        String query = "SELECT * FROM wallpapers    ORDER BY  RANDOM()  LIMIT 1";

        Log.i("Database.getRandomWallpaper([]):518      " + query);
        ResultSet resultSet = rdbStore.querySql(query, null);
        if (resultSet.goToFirstRow()) {
            do {
                int id = resultSet.getInt(resultSet.getColumnIndexForName(KEY_ID));
                String name = resultSet.getString(resultSet.getColumnIndexForName(KEY_NAME));
                if (name.length() == 0) {
                    name = "Wallpaper " + id;
                }

                wallpaper = Wallpaper.Builder()
                        .name(name)
                        .author(resultSet.getString(resultSet.getColumnIndexForName(KEY_AUTHOR)))
                        .url(resultSet.getString(resultSet.getColumnIndexForName(KEY_URL)))
                        .thumbUrl(resultSet.getString(resultSet.getColumnIndexForName(KEY_THUMB_URL)))
                        .category(resultSet.getString(resultSet.getColumnIndexForName(KEY_CATEGORY)))
                        .build();
            } while (resultSet.goToNextRow());
        }
        resultSet.close();
        return wallpaper;
    }


    private List<String> getSelectedCategories(boolean isMuzei) {

        List<String> categories = new ArrayList<>();
        String column = isMuzei ? KEY_MUZEI_SELECTED : KEY_SELECTED;

        RdbPredicates absRdbPredicates = new RdbPredicates(TABLE_CATEGORIES).equalTo(column, "1");
        ResultSet resultSet = rdbStore.query(absRdbPredicates, new String[]{KEY_NAME});
        if (resultSet.goToFirstRow()) {
            do {
                categories.add(resultSet.getString(0));
            } while (resultSet.goToNextRow());
        }
        return categories;
    }

}


